//MEGABALL

AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

ENT.iOwner = nil
ENT.HitSound = Sound("misc/rubberglove_snap.wav")

function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end
	
	local SpawnPos = tr.HitPos + tr.HitNormal * 16
	
	local ent = ents.Create( "air_ball" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	
	return ent
	
end

function ENT:Initialize()

	self.Entity:SetModel( "models/Combine_Helicopter/helicopter_bomb01.mdl" )
	self.Entity:DrawShadow( false )
	
	self.Entity:PhysicsInitSphere( 37, "metal_bouncy" )
	
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end

	self.Entity:SetCollisionBounds( Vector( -37, -37, -37 ), Vector( 37, 37, 37 ) )

	util.SpriteTrail( self.Entity, 0, Color(100, 40, 40), true, 60, 0, 0.7, 1/(18+1)*0.5, "trails/plasma.vmt" )
	
	timer.Create("T"..tostring(math.Rand(0,10000))..tostring(CurTime()/10),6,1, function()
		if ValidEntity(self.Entity) then
			local vPoint = self.Entity:GetPos() + Vector(0,0,4)
			local effectdata = EffectData()
			effectdata:SetOrigin( vPoint )
			effectdata:SetScale( 1 )
			effectdata:SetMagnitude(5)
			util.Effect( "ball_magic", effectdata )
			self.Entity:Remove()
		end	
	end)
end

function ENT:PhysicsCollide( data, physobj )
	
	if (data.Speed > 80 && data.DeltaTime > 0.2 ) then
		self.Entity:EmitSound( "weapons/baseball_hitworld1.wav" )
	end
	
	local LastSpeed = math.max( data.OurOldVelocity:Length(), data.Speed )
	local NewVelocity = physobj:GetVelocity()
	NewVelocity:Normalize()
	
	LastSpeed = math.max( NewVelocity:Length(), LastSpeed )
	
	local TargetVelocity = NewVelocity * LastSpeed * 0.6
	
	physobj:SetVelocity( TargetVelocity )
	
end

function ENT:OnTakeDamage( dmginfo )

	self.Entity:TakePhysicsDamage( dmginfo )
	
end

function ENT:Touch( entidadeTocada )

	if !ValidEntity(entidadeTocada) then return end
	if !entidadeTocada:IsPlayer() then return end
	if entidadeTocada == self.Entity.iOwner or entidadeTocada:Team() == self.Entity.iOwner:Team() then return end
	
	entidadeTocada:EmitSound(self.Entity.HitSound, 200, 100)
	
	local dano = math.random( 20, 40 )
	if entidadeTocada:Health() - dano > 0 then
		entidadeTocada:SetHealth( entidadeTocada:Health() - dano )
		
	elseif entidadeTocada:Health() - dano <= 0 then
	
		entidadeTocada.whoKilled = self.Entity.iOwner
		entidadeTocada:Kill()
	
	end
	
	self.Entity:Remove()

end



